<template>
  <j-modal
    :title="'模型训练结果'"
    :width="width"
    :visible="visible" 
    @ok="handleOk"
    :fullscreen="true"
    :okButtonProps="{ class: { 'jee-hidden': disableSubmit } }"
    @cancel="handleCancel"
    cancelText="关闭"
  > 
      <template slot="footer">
        <a-button @click="handleCancel">关闭</a-button> 
      </template>
      <a-card :bordered="false" title="模型信息">
        <a-row type="flex">
        <a-col :span="18">
            <detail-list>
              <detail-list-item term="模型编号">{{ modelBase.code }}</detail-list-item>
              <!-- <detail-list-item term="模型分类">{{ modelBase.type }}</detail-list-item> -->
              <detail-list-item term="槽号">{{ modelBase.slotNo }}</detail-list-item>
              <detail-list-item term="数据集">{{ modelBase.dataSetCode }}</detail-list-item>
              <detail-list-item term="预测目标">{{ modelBase.predictProperty }}</detail-list-item>
              <detail-list-item term="数据类型">{{ modelBase.dataType }}</detail-list-item>
              <detail-list-item term="采样间隔">{{
                modelBase.timeInterval + '  ' + modelBase.intervalUnit
              }}</detail-list-item>
              <detail-list-item term="聚合方式">{{ modelBase.method }}</detail-list-item>
              <detail-list-item term="备注">{{ modelBase.remark }}</detail-list-item>
            </detail-list> 
        </a-col>
        <a-col :span="6" style="text-align: center;font-size: 24px;"> 
           <div>RMSE（均方根误差）</div>
           <div style="margin-top: 16px;font-weight: bold;">
             {{ dataJson.RMSE }} 
           </div> 
        </a-col> 
      </a-row> 
       
      </a-card>
      <a-card :bordered="false" title="模型训练结果">
        <h4>训练过程</h4> 
        <div id="mainXL" :style="{ width: '99%', height: '420' + 'px' }"></div>
        <h4>验证数据拟合</h4>
        <div id="mainNH" :style="{ width: '99%', height: '420' + 'px' }"></div>
        <h4>特征重要度</h4>
        <div id="main" :style="{ width: '99%', height: '800' + 'px' }"></div> 
      </a-card> 
  </j-modal>
</template>

<script>
import * as echarts from 'echarts'
import { httpAction, getAction } from '@/api/manage' 
import LineChartMultid from '@/components/chart/LineChartMultid' 

import { mixinDevice } from '@/utils/mixin.js'
import PageLayout from '@/components/page/PageLayout'
import DetailList from '@/components/tools/DetailList'

const DetailListItem = DetailList.Item

export default {
  name: 'ModelBaseView', 
  components: { 
    LineChartMultid,
    PageLayout,
    DetailList,
    DetailListItem,
  },
  data() {
    return {
      title: '',
      width: 900,
      height: 500, 
      visible: false,
      disableSubmit: false,
      // url: {
      //   list: "/dataHistory/dataHistory/list"
      // },
      modelBase: {
        id: '',
        code: '',
        type: '',
        slotNo: '',
        dataSetCode: '',
        predictProperty: '',
        dataType: '',
      },
      model: {
        propName: '',
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,   
      dataJson: {},
      dataPropertyList: [],
    }
  },
  methods: {
    show(data) { 
      this.visible = true
      this.confirmLoading = false
      this.modelBase = data
      this.model.propName = ''

      this.loadDataProperty()
    },
    loadDataProperty() {
      var that = this
      httpAction('/dataProperty/dataProperty/list?pageSize=99999', {}, 'get')
        .then((res) => {
          if (res.success) {
            that.dataPropertyList = res.result.records
            that.loadModelBaseData()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {})
    },
    loadModelBaseData() {
      var that = this
      httpAction('/modelBase/modelBaseData/queryByModelBaseId?modelBaseId=' + this.modelBase.id, {}, 'get')
        .then((res) => {
          if (res.success) {
            var list = []
            that.dataJson = eval('(' + res.result.dataJson + ')')
            that.lineXLData = []
            that.loadTb() 
            var _series =[{
                            name: "训练集",
                            type: 'line',
                            showSymbol: false, 
                            itemStyle: {
                              color: 'blue',
                            }, 
                            data: that.dataJson.train_loss,
                          },
                          {
                            name: "测试集",
                            type: 'line',
                            showSymbol: false, 
                            itemStyle: {
                              color: 'rgb(255, 70, 131)', 
                            }, 
                            data: that.dataJson.valid_loss,
                          },
                        ];
            
            var yAxisMin = parseFloat(Math.min.apply(null,that.dataJson.train_loss,that.dataJson.valid_loss) - 0.1).toFixed(2)
            var yAxisMax = parseFloat(Math.max.apply(that.dataJson.train_loss,that.dataJson.valid_loss) + 0.05).toFixed(2) 
            var legendData = ['训练集','测试集'] 
            that.loadXLTb('mainXL','训练过程',_series,legendData,yAxisMin,yAxisMax,'次数','损失值');
 
            var _series2 = [{
                            name: "预测值",
                            type: 'line',
                            showSymbol: false, 
                            // itemStyle: {
                            //   color: 'blue',
                            // }, 
                            data: that.dataJson.predict_values,
                          },
                          {
                            name: "实际值",
                            type: 'line',
                            showSymbol: false, 
                            // itemStyle: {
                            //   color: 'rgb(255, 70, 131)', 
                            // }, 
                            data: that.dataJson.origin_values,
                          },
                        ];
            
            var yAxisMin2 = parseFloat(Math.min.apply(null,that.dataJson.predict_values,that.dataJson.origin_values) - 0.1).toFixed(2) 
            var yAxisMax2 = parseFloat(Math.max.apply(that.dataJson.predict_values,that.dataJson.origin_values) + 0.05).toFixed(2) 
            var legendData = ['预测值','实际值']
            that.loadXLTb('mainNH','数据拟合',_series2,legendData,yAxisMin2,yAxisMax2);
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {})
    },
    edit(record) {
      this.visible = true
      this.confirmLoading = false
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk() {
      this.$emit('close')
      this.visible = false
    },
    submitCallback() {
      this.$emit('ok')
      this.visible = false
    },
    handleCancel() {
      this.close()
    },
    loadTb() {
      var that = this
      var chartDom = document.getElementById('main')
      var myChart = echarts.init(chartDom)
      var option
      let optionSource = [
        ['', 'category'],
        // [58212, 'Matcha Latte'],
        // [78254, 'Milk Tea'],
      ]
      const importanceData = that.dataJson.importance.sort((p1,p2)=>{
        return p1.Importance - p2.Importance // 降序排
      })
      console.log("importanceData:",importanceData)
      for (let i = 0; i < importanceData.length; i++) {
        // "Importance": -0.0000034923113768278724,
        // "feature": "electric"
        var obj = importanceData[i]
        var property = that.getPropertyText(obj['feature'])
        optionSource.push([obj['Importance'], property])
      }
      option = {
        dataset: {
          source: optionSource,
        },
        grid: { containLabel: true },
        xAxis: { name: '' },
        yAxis: { type: 'category' },
        title: {
          left: 'center',
          text: '',//'[ ' + that.modelBase.code + ' ] 特征重要度',
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow',
          },
        },
        series: [
          {
            type: 'bar',
            encode: {
              // Map the "amount" column to X axis.
              x: 'amount',
              // Map the "product" column to Y axis
              y: 'product',
            },
          },
        ],
      }

      option && myChart.setOption(option)
      window.onresize = function () {
        setTimeout(function () {
          myChart.resize()
        }, 10)
      }
    },
    getPropertyText(key) {
      let filterList = this.dataPropertyList.filter((item) => item.propNo == key)
      if (filterList.length > 0) {
        return filterList[0].propName
      }
      return key
    }, 
    loadXLTb(divId,title,_series,legendData,yAxisMin,yAxisMax,xAxisName,yAxisName) {
      var that = this
      var chartDom = document.getElementById(divId)
      var myChart = echarts.init(chartDom)
      var option = {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'cross'
          },
          position: function (pt) {
            return [pt[0], '10%']
          },
        },
        title: {
          // left: 'center',
          text:''// '[ ' + that.modelBase.code + ' ] '+title,
        },
        legend: {
          data: legendData
        },
        toolbox: {
          show: true,
          feature: {
            dataZoom: {
              yAxisIndex: 'none',
            },
            dataView: { readOnly: false },
            magicType: { type: ['line', 'bar'] },
            restore: {},
            saveAsImage: {},
          },
        },
        grid: { containLabel: true },
        xAxis: {
          name: xAxisName,
          type: 'category',
          boundaryGap:false,
          // axisLabel: {
          //     interval: 30, // 显示所有刻度
          //     rotate: 30 // 将刻度旋转30度
          // }
        },
        yAxis: {
          name: yAxisName,
          type: 'value',
          // boundaryGap: [0, '100%'],
          // interval: that.yAxisInterval, //分割刻度
          min: yAxisMin,
          max: yAxisMax,
        },
        // dataZoom: [
        //   {
        //     type: 'inside',
        //     start: 0,
        //     end: 100,
        //   },
        //   {
        //     start: 0,
        //     end: 100,
        //   },
        // ],
        series: _series
      }

      option && myChart.setOption(option)
      window.onresize = function () {
        setTimeout(function () {
          myChart.resize()
        }, 10)
      }
    },
  },
}
</script>